<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <p>await需要在async函数中使用，可以用于接收一个Promise对象的返回值。</p>
    <script>

        let money = 300;

        function getTime() {
            return Math.floor(Math.random() * 3000 + 1000);
        }

        // 买菜
        function buy(name) {
            let promise = new Promise(function(resolve,reject) {
                setTimeout(() => {
                    if (money >= 50) {
                        money -= 50;
                        resolve(name);
                    } else {
                        reject(name);
                    }
                },getTime())
            });
            return promise;
        }

        async function eat() {
            let arr = ["牛肉","毛肚","鸭肠","鸭血","蟹肉","虾滑","黄喉","肥牛","脑花"];
            for (let v of arr) {
                try {
                    let r = await buy(v);
                    console.log("我买回来了:",r);
                } catch (e) {
                    console.log("我钱不够了：",e);
                } 
            }
            console.log("都买回来了，开始");
        }

        eat();

    </script>
</body>
</html>